//
//  RHDeviceLoadPieChartView.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/7.
//

#import "RHDeviceLoadPieChartView.h"
#import "DeviceChartItemView.h"
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"
#import "NSString+LenWid.h"
#import "QMUILabel+LHAdd.h"
#import "RHMaskView.h"
#import "RHLeftAxisFormatter.h"
#import "RHRightAxisFormatter.h"
#import "RHPieChartViewLegend.h"

@interface RHDeviceLoadPieChartView()
@property (nonatomic ,copy) NSArray *colorList;
//前一天
@property (nonatomic ,strong) QMUIButton *l_btn;
//后一天
@property (nonatomic ,strong) QMUIButton *r_btn;
//日期
@property (nonatomic ,strong) QMUIButton *timeBtn;

//左边Y轴单位
@property (nonatomic, strong) QMUILabel *leftUnitLab;
//右边Y轴单位
@property (nonatomic, strong) QMUILabel *rightUnitLab;

//气泡
@property (nonatomic, strong) RHMaskView *maskView;
/// 图表
@property (nonatomic, strong) PieChartView *pieChartView;
//年,月,日
@property (nonatomic ,assign) NSInteger type;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) UIView *scrollBgView;

@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) NSMutableArray *itemsArray;


@end
@implementation RHDeviceLoadPieChartView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type{
    self = [super initWithFrame:frame];
    if (self) {
        self.colorList = @[@"#FDAF37",@"#55E4B9",@"#589CFB",@"#77E4D1",@"#F9CF4A"];
        self.type = type;
        [self setupUI];
        [self setPieChartData];
    }
    return self;
}
- (void)setLoadDic:(NSDictionary *)loadDic
{
    _loadDic = loadDic;
    [self setPieChartData];
    RHPieChartViewLegend *legend_solar = [self viewWithTag:100];
    legend_solar.percentLab.text = [NSString stringWithFormat:@"%@%%",loadDic[@"pv"]?[NSString stringWithFormat:@"%ld",[loadDic[@"pv"]integerValue]]:@"--"];
    
    RHPieChartViewLegend *legend_battery = [self viewWithTag:101];
    legend_battery.percentLab.text = [NSString stringWithFormat:@"%@%%",loadDic[@"bat"]?[NSString stringWithFormat:@"%ld",[loadDic[@"bat"]integerValue]]:@"--"];
    
    RHPieChartViewLegend *legend_grid = [self viewWithTag:102];
    legend_grid.percentLab.text = [NSString stringWithFormat:@"%@%%",loadDic[@"grid"]?[NSString stringWithFormat:@"%ld",[loadDic[@"grid"]integerValue]]:@"--"];
}

- (void)setChartModel:(DevChartModel *)chartModel{
    _chartModel = chartModel;
    self.selectIndex = _chartModel.timeType;
    [self setPieChartData];
    NSString *timeStr;
    if (_chartModel.timeType == TimeType_Day) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString *dateTime = [formatter stringFromDate:date];
        timeStr = dateTime;
        [_r_btn setEnabled:[date isToday]?NO:YES];
    }else if (_chartModel.timeType == TimeType_Month) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%02ld-%02ld",[date year],[date month]];
        [_r_btn setEnabled:[[NSDate date] monthsLaterThan:date]?YES:NO];
    }else if (_chartModel.timeType == TimeType_Year){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%ld",[date year]];
        [_r_btn setEnabled:[[NSDate date] yearsLaterThan:date]?YES:NO];
    }else{
        timeStr = @"";
    }

    [self.timeBtn setTitle:ValidStr(timeStr)?timeStr:@"" forState:UIControlStateNormal];


}

-(void)setPieChartData
{
    NSArray *dataArr = @[@"光伏".rh_localized,@"电池".rh_localized,@"电网".rh_localized];
    
    NSArray *dic_key = @[@"pv",@"bat",@"grid"];
    __block NSInteger total = 0;
    for (NSString *key in self.loadDic.allKeys) {
       total += [self.loadDic[key] integerValue];
    }
    NSMutableArray *values = [[NSMutableArray alloc] init];
    [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger value = [self.loadDic[dic_key[idx]] integerValue];
        if(total == 0){
            if(idx == 1){
                value = 1;
            }else{
                value = 0;
            }
        }
    
        [values addObject:[[PieChartDataEntry alloc] initWithValue:value label:dataArr[idx] icon:nil]];
    }];
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithEntries:values label:@""];
    dataSet.drawValuesEnabled = NO;
    dataSet.drawIconsEnabled = NO;
    //饼图距离边距距离。默认18
    dataSet.selectionShift = 0;
    //饼片之间的距离
    dataSet.sliceSpace = 2.0;
    dataSet.iconsOffset = CGPointMake(0, 40);
    dataSet.colors = @[kCOLOR_HEX(@"FDAF37"),kCOLOR_HEX(@"55E4B9"),kCOLOR_HEX(@"589CFB")];
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" %";
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.blackColor];
    
    self.pieChartView.data = data;
    
}



- (void)setupUI{
    [self setBackgroundColor:UIColor.whiteColor];
    UIView *itemBgView = [[UIView alloc] init];
    [itemBgView setBackgroundColor:UIColor.whiteColor];
    [self addSubview:itemBgView];
    //不显示 年月日,只有日
    itemBgView.hidden = YES;
    
    kWeakSelf;
    UIView *line = kView;
    line.backgroundColor = CMainColorGreen;
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.offset(2);
    }];
    line.hidden = YES;
    
    NSArray *titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    if (self.type == 0) {
        titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    }else if (self.type == 1){
        titles = @[@"日".rh_localized,@"月".rh_localized];
    }else if (self.type == 2){
        titles = @[@"日".rh_localized];
    }
    __block QMUIButton *lastbtn;
   
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:_nameStr];
        //CGSize size = [self.nameLab getLableSizeWithAttStr:attr maxHeight:18];
        QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundColor:UIColor.whiteColor];
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        CGFloat width = [obj getStringWidthFont:btn.titleLabel.font limitHeight:200];
        [itemBgView addSubview:btn];
        
        if(idx == 0){
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(btn.mas_bottom).offset(0);
                    make.centerX.equalTo(btn);
                    make.width.equalTo(btn).offset(-10);
            }];
        }
        
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf btnAction:idx];
            [line mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(x.mas_bottom).offset(0);
                    make.centerX.equalTo(x);
                    make.width.equalTo(x).offset(-10);
                    make.height.offset(2);
            }];
            
        }];
        
        
        [RACObserve(weakSelf, selectIndex) subscribeNext:^(id  _Nullable x) {
            NSInteger index = [x integerValue];
            NSLog(@"--->index:%ld  button:%@",index,btn);
            if (index == idx) {
                [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"323233") forState:UIControlStateNormal];
                btn.backgroundColor = [UIColor colorWithHexString:@"5DD8AB" alpha:0.25];
            }else{
                [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"969799") forState:UIControlStateNormal];
                btn.backgroundColor = UIColor.whiteColor;
            }
            
        }];
        
        if (!lastbtn) {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0.5);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }else{
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastbtn.mas_right).offset(2);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }
        lastbtn = btn;
    }];
    
    [lastbtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-0.5);
    }];
    
    [itemBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(20);
    }];
    
    //全屏
    QMUIButton *full_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [full_btn setImagePosition:QMUIButtonImagePositionRight];
    [full_btn setImage:[UIImage imageNamed:@"full_screen"] forState:UIControlStateNormal];
    [full_btn setTitle:@"" forState:UIControlStateNormal];
    full_btn.hidden = YES;
    [self addSubview:full_btn];
    
    //时间
    QMUIButton *dateBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [dateBtn setBackgroundColor:UIColor.whiteColor];
    [dateBtn setTitle:@"2023-08-09" forState:UIControlStateNormal];
    [dateBtn setImagePosition:QMUIButtonImagePositionRight];
    dateBtn.spacingBetweenImageAndTitle = 5;
    [dateBtn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
    [dateBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:dateBtn];
    self.timeBtn = dateBtn;
    
    //上一天
    _l_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_l_btn setImagePosition:QMUIButtonImagePositionRight];
    [_l_btn setImage:[UIImage imageNamed:@"day_left"] forState:UIControlStateNormal];
    [self addSubview:_l_btn];
    
    //下一天
    _r_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_r_btn setImagePosition:QMUIButtonImagePositionRight];
    [_r_btn setImage:[UIImage imageNamed:@"day_right"] forState:UIControlStateNormal];
    [self addSubview:_r_btn];

    [self addSubview:self.pieChartView];
    
    //添加单位
    QMUILabel *leftUnitLab = [[QMUILabel alloc]init];
    leftUnitLab.textColor = UIColor.lightGrayColor;
    leftUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:leftUnitLab];
    self.leftUnitLab = leftUnitLab;
    
    [leftUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.pieChartView).offset(5);
        make.bottom.equalTo(weakSelf.pieChartView.mas_top).offset(0);
    }];
    
    
    //下面的曲线标签按钮
    _scrollBgView = [[UIView alloc] init];
    [_scrollBgView setBackgroundColor:UIColor.orangeColor];
    [self addSubview:_scrollBgView];
    
    _scroll = [[UIScrollView alloc] init];
    [_scroll setShowsHorizontalScrollIndicator:NO];
    _scroll.backgroundColor = [UIColor whiteColor];
    [_scrollBgView addSubview:_scroll];
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor whiteColor];
    [_scroll addSubview:_contentView];
    
    __block RHPieChartViewLegend *lastItem;
 
    NSArray *dataArr = @[@"光伏".rh_localized,@"电池".rh_localized,@"电网".rh_localized];
    NSArray *valueArr = @[ValidNullDataToString(self.loadDic[@"pv"], @"--"),
                          ValidNullDataToString(self.loadDic[@"bat"], @"--"),
                          ValidNullDataToString(self.loadDic[@"grid"], @"--")];
    [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHPieChartViewLegend *legendView = [[RHPieChartViewLegend alloc] init];
        legendView.tag = 100+ idx;
        legendView.titleLab.text = dataArr[idx];
        legendView.percentLab.text = [NSString stringWithFormat:@"%@%%",valueArr[idx]];
        [legendView.markLab setBackgroundColor:FontColor(self.colorList[idx])];
//        [itemView shadow:UIColor.blackColor opacity:0.1 radius:5 offset:CGSizeMake(0, 1)];
        [_contentView addSubview:legendView];
        [self.itemsArray addObject:legendView];

        if (!lastItem) {
            [legendView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(25);
                make.top.mas_offset(5);

            }];

        }else{
            [legendView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastItem.mas_right).offset(35);
                make.top.mas_offset(5);

            }];

        }
        lastItem = legendView;
    }];

    [lastItem mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-25);
    }];

    
    //饼状图
    [self.pieChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(dateBtn.mas_bottom).offset(10);
       
    }];
    
    [self.scrollBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(self.pieChartView.mas_bottom).offset(20);
        make.bottom.mas_offset(-10);
        make.height.mas_equalTo(50);
       
    }];
    
    
    
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    [full_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 40));
        make.right.mas_offset(-5);
        make.centerY.equalTo(lastbtn);
    }];
    
    
    
    [dateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.size.mas_equalTo(CGSizeMake(80, 30));
        make.centerX.mas_offset(0);
    }];
    
    [_l_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.right.equalTo(dateBtn.mas_left);
    }];

    [_r_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.left.equalTo(dateBtn.mas_right);
    }];
    
    
   
    
    [[full_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf fullAction];
    }];
    
    [[_l_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往前
        if (weakSelf.subTimeBlock) {
            weakSelf.subTimeBlock();
        }
    }];
    
    [[_r_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往后
        if (weakSelf.addTimeBlock) {
            weakSelf.addTimeBlock();
        }
    }];
    
    [[dateBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (weakSelf.changeTimeBlock) {
            weakSelf.changeTimeBlock();
        }
    }];
    NSLog(@"--------2222:%@",NSStringFromCGRect(lastItem.frame));
    
    [self.scrollBgView setNeedsLayout];
    [self.scrollBgView layoutIfNeeded];
    NSLog(@"--------3333:%@",NSStringFromCGRect(lastItem.frame));
    
    if(lastItem.right+25 < kUI_WINDOW_W-40){
        [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.offset(lastItem.right + 25);
            make.top.bottom.mas_offset(0);
            make.centerX.mas_offset(0);
        }];
        
    }
    
    
}


- (void)fullAction{
    if (self.fullChartBlock) {
        self.fullChartBlock();
    }
}

- (void)btnAction:(NSInteger)index{
    if (self.selectTopToolBlock) {
        self.selectTopToolBlock(index);
    }
    
    if (index == -1) {//自定义参数设置
        return;
    }
    
    self.selectIndex = index;
    NSLog(@"---->选择的下标:%d",index);
    if (self.selectIndex == 1) {//Day
        
    }
    
    if (self.selectIndex == 2) {//Month
        
    }
    
    if (self.selectIndex == 3) {//Year
        
    }
    
    if (self.selectIndex == 4) {//Total
        
    }
}



- (PieChartView *)pieChartView{
    if (!_pieChartView) {
        _pieChartView = [[PieChartView alloc]init];
        //是否使用百分比
        _pieChartView.usePercentValuesEnabled = YES;
        //标记，指示是否应该绘制入口标签
        _pieChartView.drawEntryLabelsEnabled = NO;
        _pieChartView.drawSlicesUnderHoleEnabled = NO;
        //空心半径占比
        _pieChartView.holeRadiusPercent = 0.58;
        //半透明空心半径占比
        _pieChartView.transparentCircleRadiusPercent = 0.61;
        //半透明空心的颜色
//        _pieChartView.transparentCircleColor = UIColor.whiteColor;
        _pieChartView.chartDescription.enabled = NO;
        [_pieChartView setExtraOffsetsWithLeft:0 top:0 right:0 bottom:0];
        //饼图周围的最小偏移量，影响饼图大小。默认0
        _pieChartView.minOffset = 0;
        NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:@"中心文字"];
        _pieChartView.centerAttributedText = centerText;
        //饼状图是否是空心
        _pieChartView.drawHoleEnabled = YES;
        _pieChartView.rotationAngle = 0.0;
        //是否允许拖拽旋转
        _pieChartView.rotationEnabled = NO;
        //设置为false，禁止点击手势高亮显示值，值仍然可以通过拖动或编程方式突出显示
        _pieChartView.highlightPerTapEnabled = NO;
        //是否显示中心文字
        _pieChartView.drawCenterTextEnabled = NO;
        //不展示图例
        _pieChartView.legend.enabled = NO;
        
        ChartLegend *legend = _pieChartView.legend;
        legend.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;
        legend.verticalAlignment = ChartLegendVerticalAlignmentBottom;
        legend.orientation = ChartLegendOrientationHorizontal;
        legend.drawInside = NO;
        legend.xEntrySpace = 15;
        legend.yEntrySpace = 0;
        legend.yOffset = 0.0;
        legend.formSize = 10;
        legend.font = kSYSTEMFONT(12);
    
    }
    return _pieChartView;
}




#pragma mark ------ lazy load

- (NSMutableArray *)itemsArray{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}



@end
